from fastapi import APIRouter, UploadFile, File, HTTPException
from pydantic import BaseModel
from app.services.inference import run_inference
from app.services.demo_inference import run_demo_inference, is_demo_mode
from app.services.suggestions import get_suggestions
import logging

router = APIRouter()
logger = logging.getLogger(__name__)

class DiagnosisResponse(BaseModel):
    moisture: str
    moisture_confidence: float
    pest: str
    pest_confidence: float
    suggestions: list[str]
    demo_mode: bool = False

class ErrorResponse(BaseModel):
    error: str
    detail: str

@router.post("/diagnose", response_model=DiagnosisResponse)
async def diagnose(file: UploadFile = File(...)):
    # 验证文件格式
    if not file.content_type.startswith('image/'):
        raise HTTPException(
            status_code=400, 
            detail="只支持图片文件格式 (JPEG, PNG, etc.)"
        )
    
    # 验证文件大小 (限制为10MB)
    if file.size and file.size > 10 * 1024 * 1024:
        raise HTTPException(
            status_code=400, 
            detail="文件大小不能超过10MB"
        )
    
    try:
        # 读取上传的图像
        image_bytes = await file.read()
        
        # 检查是否为演示模式
        demo_mode = is_demo_mode()
        
        if demo_mode:
            logger.info("使用演示模式进行诊断")
            # 使用演示模式推理
            moisture_result, moisture_conf = run_demo_inference(image_bytes, model_type="moisture")
            pest_result, pest_conf = run_demo_inference(image_bytes, model_type="pest")
        else:
            logger.info("使用训练好的模型进行诊断")
            # 使用真实模型推理
            moisture_result, moisture_conf = run_inference(image_bytes, model_type="moisture")
            pest_result, pest_conf = run_inference(image_bytes, model_type="pest")

        # 置信度检查
        if moisture_conf < 0.6 or pest_conf < 0.6:
            raise HTTPException(
                status_code=422,
                detail="模型置信度过低，请重新拍摄更清晰的图片"
            )

        suggestions = get_suggestions(moisture_result, pest_result)

        return {
            "moisture": moisture_result,
            "moisture_confidence": moisture_conf,
            "pest": pest_result,
            "pest_confidence": pest_conf,
            "suggestions": suggestions,
            "demo_mode": demo_mode
        }
        
    except Exception as e:
        logger.error(f"诊断过程中发生错误: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail="诊断服务暂时不可用，请稍后重试"
        )

@router.get("/status")
async def get_status():
    """获取服务状态"""
    demo_mode = is_demo_mode()
    return {
        "status": "running",
        "demo_mode": demo_mode,
        "message": "演示模式" if demo_mode else "正常模式"
    }